#include "ServerFunc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

//文件结构体
struct PacketFile
{
    FILE *f;//文件指针
    long FileSize;//文件大小
    long currentPosition;//当前位置
};

//serverfunc.c 打开文件 并初始化文件结构体(堆) 返回文件结构体指针
PackFile * PacketFileInit(const char * FilePath)
{
    PackFile *pf = (PackFile *)malloc(sizeof(PackFile));
    if(pf == NULL)
    {
        printf("PacketFileInit malloc error!\n");
        return NULL;
    }

    pf->f = fopen(FilePath,"r");
    if(pf->f == NULL)
    {
        printf("打开|%s|文件失败!\n",FilePath);
        free(pf);
        return NULL;
    }
    //计算文件大小
    fseek(pf->f,0,SEEK_END);
    pf->FileSize = ftell(pf->f);
    fseek(pf->f,0,SEEK_SET);

    pf->currentPosition = 0;
    printf("文件大小：%ld,文件位置:%ld\n",pf->FileSize,pf->currentPosition);
    return pf;
}

//clientfunc.c 从文件f读取size大小的数据，并更新当前位置
void ReadFromFile(PackFile * f, void * p, int * size)
{
    if(*size + f->currentPosition > f->FileSize)
    {
        *size = f->FileSize - f->currentPosition;
    }
    fread(p,*size,1,f->f);
    f->currentPosition += *size;
}

//clientfunc.c 判断文件是否已经读完
bool IsFileEnd(PackFile * f)
{
    return f->currentPosition == f->FileSize;
}

//server.c 从文件路径中获取文件名称（堆） 返回地址
char * GetFileNameFromPath(const char * filePath)
{
    char str[ContentSize] = {0};
    strcpy(str,filePath);

    char *dest = strtok(str,"/");
    char *fileName = NULL;
    while(dest != NULL)
    {
        fileName = dest;
        dest = strtok(NULL,"/");
    }
    char *result = strdup(fileName);
    return result;
}

//clientfunc.c 关闭文件 释放文件结构体
void ClearPacketFile(PackFile * f)
{
    fclose(f->f);
    free(f);
}

long GetFilesize(const char *filePath)
{
    PackFile *pf = PacketFileInit(filePath);
    long filesize = pf->FileSize;
    ClearPacketFile(pf);
    return filesize;
}

